
//
//  BDPublishViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/20.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPublishViewController.h"
#import "BDPublishTableViewCell.h"
#import "BDTextView.h"
#import "CameraPhotoBehavior.h"
#import "BDPubishLocationViewController.h"
#import "DatePickbehavior.h"
#import "BDUserModel.h"
#import "LiuqsEmoticonKeyBoard.h"
#import "BDEmojiKeyboardBtton.h"
#import "BDLocationServer.h"
#import "BDTishiViewController.h"
#import "BDCityInfo.h"
#import "BDButtonAlert.h"

@interface BDPublishViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, strong) NSString *xiaofeiTime;
@property (nonatomic, strong) NSString *dianpuName;
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSString *phone;
@property (nonatomic, strong) NSString *price;
@property (nonatomic, strong) NSString *location;
@property (nonatomic, strong) NSString *zhutiShoujia;
@property (nonatomic, assign) double longitude;
@property (nonatomic, assign) double latitude;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) BDTextView *textView;
@property (nonatomic, strong) UIView *blakeView;
@property (nonatomic, strong) LiuqsEmoticonKeyBoard *emoticonKeyborad;

@property (nonatomic, strong) NSString *province;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *district;

@end

@implementation BDPublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"发表");
    [self bindRAC];
    [self yy_setDatasource];
    [self.tableView reloadData];
    self.emoticonKeyborad.hidden = YES;
    self.emoticonKeyborad.top = kBDScreenHeight;
}

- (void)bindRAC{
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        if (self.emoticonKeyborad.bottom == kBDScreenHeight) {
            [UIView animateWithDuration:0.3 animations:^{
                self.emoticonKeyborad.top = kBDScreenHeight;
            } completion:^(BOOL finished) {
                self.emoticonKeyborad.hidden = YES;
            }];
        }
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [[NSNotificationCenter defaultCenter] postNotificationName:UIKeyboardWillShowNotification object:nil];
    }
}

- (void)yy_setDatasource{
    self.datasource = @[@{@"image":@"time", @"title":ASLocalizedString(@"消费时间"), @"subTitle":self.xiaofeiTime ? self.xiaofeiTime : @"", @"placeHold":ASLocalizedString(@"填写消费时间"), @"enable":@NO},
                        @{@"image":@"dianpu", @"title":ASLocalizedString(@"店铺名称"), @"subTitle":self.dianpuName ? self.dianpuName : @"", @"placeHold":ASLocalizedString(@"填写店铺名称")},
                        @{@"image":@"fabiao_fenlei", @"title":ASLocalizedString(@"选择分类"), @"subTitle":[self.type isNotEmpty]? self.type : @"", @"placeHold":ASLocalizedString(@"选择对应分类"), @"right":@YES, @"enable":@NO
                          },
                        @{@"image":@"phone", @"title":ASLocalizedString(@"联系方式"), @"subTitle":self.phone ? self.phone : @"", @"placeHold":ASLocalizedString(@"填写联系方式")},
                        @{@"image":@"xiaofei", @"title":ASLocalizedString(@"消费价格"), @"subTitle":self.price ? self.price : @"", @"placeHold":ASLocalizedString(@"填写消费价格"), @"keyoardNumber":@(UIKeyboardTypeNumberPad)},
                        @{@"image":@"dizhi", @"title":ASLocalizedString(@"显示位置"), @"subTitle":self.location ? self.location : @"", @"placeHold":@"", @"right":@YES, @"enable":@NO
                          },
                        @{@"image":@"jifen", @"title":ASLocalizedString(@"主题售价"), @"subTitle":self.zhutiShoujia ? self.zhutiShoujia : @"", @"placeHold":@"0", @"keyoardNumber":@(UIKeyboardTypeDecimalPad)}].mutableCopy;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDPublishTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"publishCell" forIndexPath:indexPath];
    [cell configeWithDic:self.datasource[indexPath.row] textFieldBlock:^(NSString *text) {
        switch (indexPath.row) {
            case 1:
                self.dianpuName = text;
                break;
            case 3:
                self.phone = text;
                break;
            case 4:
                self.price = text;
                break;
            case 6:
                self.zhutiShoujia = text;
                break;
            default:
                break;
        }
        [self yy_setDatasource];
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak BDPublishViewController *weakSelf = self;
    if (indexPath.row == 2) {
        [BDButtonAlert showWithTitle:ASLocalizedString(@"选择分类")buttonTitleArray:@[ASLocalizedString(@"水疗"), @"KTV", ASLocalizedString(@"夜总会"), ASLocalizedString(@"酒吧"), ASLocalizedString(@"沐足"), ASLocalizedString(@"其他")] finishBlock:^(NSString *buttonTitle) {
            weakSelf.type = buttonTitle;
            [weakSelf yy_setDatasource];
            [weakSelf.tableView reloadData];
        }];
    }
    else if (indexPath.row == 5) {
        BDPubishLocationViewController *locationVC = [[BDPubishLocationViewController alloc] initWithFinishBlock:^(AMapPOI *poi) {
            weakSelf.location = poi.address;
            weakSelf.longitude = poi.location.longitude;
            weakSelf.latitude = poi.location.latitude;
            weakSelf.province = poi.province;
            weakSelf.city = poi.city;
            weakSelf.district = poi.district;
            
            [self yy_setDatasource];
            [self.tableView reloadData];
        }];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:locationVC] animated:YES completion:nil];
    }else if (indexPath.row == 0) {
        [DatePickbehavior getDateBehaviorByCurrentDate:self.xiaofeiTime startDate:nil endDate:datePickNow finishBlock:^(NSString *finialDate) {
            self.xiaofeiTime = finialDate;
            [self yy_setDatasource];
            [self.tableView reloadData];
        }];
    }
}

- (UIView *)customHeaderView{
    
    UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 227)];
    bkView.tag = 5333;
    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 217)];
    [bkView addSubview:contentView];
    contentView.backgroundColor = [UIColor whiteColor];
    contentView.tag = 5444;
    
    self.textView = [[BDTextView alloc]initWithFrame:CGRectMake(10, 0, kBDScreenWidth - 20, 120)];
    [_textView setPlaceHolderFont:[UIFont systemFontOfSize:15]];
    [_textView setPlaceholder:ASLocalizedString(@"发表内容请遵守中华人民共和国法律法规，禁止发表不健康及政治等违规内容。")];
    [contentView addSubview:_textView];
    
    NSArray *imageArray = @[@"pic_1",@"biaoqing"];//,@"jing"
    CGFloat space = 40;
    
    for (int i = 0; i < imageArray.count; i++) {
        UIButton *button = nil;
        if (i == 0) {
            button = [UIButton buttonWithType:UIButtonTypeCustom];
        }else{
            button = [BDEmojiKeyboardBtton buttonWithType:UIButtonTypeCustom];
        }
        button.size = CGSizeMake(25, 25);
        button.left = 10 + (25 + space) * i;
        button.bottom = contentView.height - 10;
        [button setBackgroundImage:[UIImage imageNamed:imageArray[i]] forState:UIControlStateNormal];
        button.tag = 1000 + i;
        
        if (i == 1) {
            [button setBackgroundImage:[UIImage imageNamed:@"jianpan"] forState:UIControlStateSelected];
            button.endWindowEditingWhenTouch = NO;
        }
        
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (i == 0) {
                [[CameraPhotoBehavior behavior] getPhotoWithtargetVC:self FinishBlock:^(UIImage *image) {
                    CGFloat imageSide = (kBDScreenWidth - 40) / 3;
                    UIImageView *imageView = [[UIImageView alloc] init];
                    imageView.size = CGSizeMake(imageSide, imageSide);
                    UIButton *delButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    delButton.size = CGSizeMake(20, 20);
                    [delButton setBackgroundImage:[UIImage imageNamed:@"imageDele"] forState:UIControlStateNormal];
                    delButton.layer.masksToBounds = YES;
                    delButton.layer.cornerRadius = 5;
                    delButton.center = CGPointMake(imageView.width, 0);
                    [imageView addSubview:delButton];
                    imageView.clipsToBounds = NO;
                    imageView.userInteractionEnabled = YES;
                    
                    [[delButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                        [delButton.superview removeFromSuperview];
                        [self.imageArray removeObject:delButton.superview];
                        [self reloadTableHeaderView];
                    }];
                    imageView.image = image;
                    [contentView addSubview:imageView];
                    [self.imageArray addObject:imageView];
                    [self reloadTableHeaderView];
                }];
            }else if (i == 1) {
                // BDLog(ASLocalizedString(@"点击了表情按钮啊"));
                [self.textView resignFirstResponder];
                self.emoticonKeyborad.hidden = NO;
                if (self.emoticonKeyborad.bottom != kBDScreenHeight) {
                    self.emoticonKeyborad.top = kBDScreenHeight;
                    [UIView animateWithDuration:0.3 animations:^{
                        self.emoticonKeyborad.bottom = kBDScreenHeight;
                    }];
                }
            }
        }];
        
        [contentView addSubview:button];
    }
    
    return bkView;
}

- (void)reloadTableHeaderView{
    CGFloat imageSide = (kBDScreenWidth - 40) / 3;
    UIView *contentView = [self.tableView.tableHeaderView viewWithTag:5444];
    
    for (int i = 0; i < self.imageArray.count; i++) {
        UIImageView *imageView = self.imageArray[i];
        imageView.frame = CGRectMake(10 + i % 3 * (imageSide + 10), 125 + i / 3 * (imageSide + 10), imageSide, imageSide);
    }
    
    if (self.imageArray.count % 3 == 0) {
        contentView.height = 45 + 120 + 10 + self.imageArray.count / 3 * (imageSide + 10);
    }else {
        contentView.height = 45 + 120 + 10 + (self.imageArray.count / 3 + 1) * (imageSide + 10);
    }
    
    
    UIView *bkView = [self.tableView.tableHeaderView viewWithTag:5333];
    bkView.height = contentView.height + 10;
    
    NSArray *buttonImageArray = @[@"pic_1",@"biaoqing"];
    for (int i = 0; i < buttonImageArray.count; i++) {
        UIButton *button = [contentView viewWithTag:1000 + i];
        button.bottom = contentView.height - 10;
    }
    [self.tableView reloadData];
}

- (UIView *)customFooterView{
    UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 100)];
    UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    publishButton.size = CGSizeMake(kBDScreenWidth- 20, 40);
    publishButton.left = 10;
    publishButton.top = 15;
    publishButton.backgroundColor = [UIColor colorWithHexString:@"#4d7aad"];
    [publishButton setTitle:ASLocalizedString(@"发送")forState:UIControlStateNormal];
    [publishButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    publishButton.titleLabel.font = [UIFont systemFontOfSize:17];
    
    [[publishButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSString *plainStr = [self.textView.attributedText getPlainString];
        
        NSString *alert = nil;
        if (plainStr.length == 0) {
            alert = ASLocalizedString(@"请输入文本内容");
        }else if (![self.type isNotEmpty]){
            alert = ASLocalizedString(@"请选择分类");
        }else if (self.zhutiShoujia.floatValue != 0 && self.zhutiShoujia != nil) {
            if (![self.xiaofeiTime isNotEmpty]) {
                //消费日期
                alert = ASLocalizedString(@"请选择消费日期");
            }else if (![self.dianpuName isNotEmpty]) {
                //店铺名称
                alert = ASLocalizedString(@"请输入店铺名称");
            }else if (![self.phone isNotEmpty]) {
                //联系方式
                alert = ASLocalizedString(@"请输入联系方式");
            }else if (![self.location isNotEmpty]) {
                //具体位置
                alert = ASLocalizedString(@"请选择位置");
            }else if (![self.price isNotEmpty]) {
                //消费情况
                alert = ASLocalizedString(@"请输入消费金额");
            }
        }
        if ([alert isNotEmpty]) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
            return;
        }
        
        
        NSString *url = [NSString stringWithFormat:@"%@post", KBDBaseURL];
        NSMutableDictionary *para = @{@"post":plainStr,
                                      @"category":@([BDButtonAlert getTypeidWitTypeString:self.type])}.mutableCopy;
        //消费日期
        if ([self.xiaofeiTime isNotEmpty]) {
            [para setObject:self.xiaofeiTime forKey:@"consumed_at"];
        }
        //price
        if ([self.zhutiShoujia isNotEmpty]) {
            [para setObject:self.zhutiShoujia forKey:@"price"];
        }else{
            [para setObject:@"0" forKey:@"price"];
        }
        //店铺
        if ([self.dianpuName isNotEmpty]) {
            [para setObject:self.dianpuName forKey:@"shop"];
        }
        //longitude
        if (self.longitude != 0) {
            [para setObject:@(self.longitude) forKey:@"longitude"];
        }
        //latitude
        if (self.latitude != 0) {
            [para setObject:@(self.latitude) forKey:@"latitude"];
        }
        //address
        if ([self.location isNotEmpty]) {
            [para setObject:self.location forKey:@"address"];
        }
        //contact
        if ([self.phone isNotEmpty]) {
            [para setObject:self.phone forKey:@"contact"];
        }
        //consumption
        if ([self.price isNotEmpty]) {
            [para setObject:self.price forKey:@"consumption"];
        }
        
        
        if (![self.province isNotEmpty]) {
            BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
            self.province = locationModel.province;
            self.city = locationModel.city;
            self.district = locationModel.district;
        }
        BDCityInfo *provinceInfo = [BDCityInfo getCityWithName:self.province];
        BDCityInfo *cityInfo = [BDCityInfo getCityWithName:self.city];
        BDCityInfo *districtInfo = [BDCityInfo getCityWithName:self.district];
        
        [para setObject:[NSString stringWithFormat:@"%@", @(provinceInfo.infoID)] forKey:@"province_id"];
        [para setObject:[NSString stringWithFormat:@"%@", @(cityInfo.infoID)] forKey:@"city_id"];
        [para setObject:[NSString stringWithFormat:@"%@", @(districtInfo.infoID)] forKey:@"district_id"];
        
        NSString *headValid = [BDUserModel getHeaderValidation];
        
        NSMutableArray *dataArray = [NSMutableArray array];
        for (int i = 0; i < self.imageArray.count; i++) {
            UIImageView *imageView = self.imageArray[i];
            [dataArray addObject:UIImageJPEGRepresentation(imageView.image, 1)];
        }
        
        [MBManager showLoadingAlert:nil clickHidden:NO clickBlock:nil];
        
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid name:@"images[]" dataArray:dataArray automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:ASLocalizedString(@"发表成功")clickHidden:NO clickBlock:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
            [MBManager hideAlert];
            if (error.code == 40005) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"抱歉，此内容违反了《夜城社区管理规定(试行)》或相关法规政策，无法进行指定操作")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:@[ASLocalizedString(@"查看帮助")] clickBlock:^(NSInteger index) {
                    if (index == 1) {
                        BDTishiViewController *tishiVC = [[BDTishiViewController alloc] init];
                        tishiVC.xieyiType = BDXieyiTypePost;
                        [self.navigationController pushViewController:tishiVC animated:YES];
                    }
                }];
            }else {
                [MBManager showBriefAlert:ASLocalizedString(@"发表失败")clickHidden:NO clickBlock:nil];
            }
            
        }];
    }];
    
    [bkView addSubview:publishButton];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, kBDScreenWidth -20, 30)];
    label.numberOfLines=0;
    label.textColor=[UIColor colorWithHexString:@"#767676"];
    label.font = [UIFont systemFontOfSize:12];
    label.text = ASLocalizedString(@"友情提示：当主题售价大于0元时，店铺名称、联系方式、店铺地址必须填写。");
    label.top = publishButton.bottom + 10;
    [bkView addSubview:label];
    
    return bkView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        UITableViewController* tvc=[[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
        [self addChildViewController:tvc];
        [tvc.view setFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight)];
        self.tableView = tvc.tableView;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = [self customHeaderView];
        [_tableView registerClass:[BDPublishTableViewCell class] forCellReuseIdentifier:@"publishCell"];
        _tableView.sectionFooterHeight = 10;
        _tableView.tableFooterView = [self customFooterView];
        [self.view addSubview:self.tableView];
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (NSMutableArray *)imageArray{
    if (!_imageArray) {
        self.imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (LiuqsEmoticonKeyBoard *)emoticonKeyborad{
    if (!_emoticonKeyborad) {
        self.emoticonKeyborad = [LiuqsEmoticonKeyBoard showKeyBoardInView:self.view];
        _emoticonKeyborad.textView = self.textView;
        [self.view addSubview:_emoticonKeyborad];
    }
    return _emoticonKeyborad;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
